import paramiko
import requests


def get_server_info(hostname, usernme, private_key_path):
    """
    :param hostname: 主机名或ip
    :param usernme:  登录用户名
    :param key_path:  私钥路径
    :return: 资产信息
    """
    private_key = paramiko.RSAKey.from_private_key_file(private_key_path)
    transport = paramiko.Transport(hostname, 22)
    transport.connect(username=usernme, pkey=private_key)

    ssh = paramiko.SSHClient()
    ssh._transport = transport
    try:
        stdin, stdout, stderr = ssh.exec_command('ifconfig')
        # 资产信息进行筛选，返回
        return stdout.read().decode()
    except Exception as e:
        print(e)
    finally:
        transport.close()


def run():
    host = "10.0.0.3"
    info = get_server_info(hostname=host, usernme="root", private_key_path=r'c:/Users/bertwu/.ssh/id_rsa')
    # 信息发送给api平台，进行入库
    url = "http://127.0.0.1:5000/api/index/"
    data = {"host": host, "info": info}
    res = requests.post(url=url, json=data)
    print(res.json())


if __name__ == '__main__':
    run()
